package com.ym.livedemo.api

import android.os.Handler
import android.os.Looper
import okhttp3.Interceptor
import okhttp3.Response
import org.json.JSONObject
import java.io.IOException
import java.nio.charset.Charset

/**
 * Created by 赵杰 on 2019-10-15.
 */

class AppHttpInterceptor : Interceptor {
    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        val originalResponse = chain.proceed(chain.request())
        val responseBody = originalResponse.body
        val source = responseBody!!.source()
        source.request(java.lang.Long.MAX_VALUE) // Buffer the entire body.
        val buffer = source.buffer()
        var charset = Charset.forName("UTF-8")
        val contentType = responseBody.contentType()
        if (contentType != null) {
            charset = contentType.charset(Charset.forName("UTF-8"))
        }

//        loge(buffer.clone().readString(charset))

        val jsonObject = JSONObject(buffer.clone().readString(charset))

        when (jsonObject.opt("code")) {
            500, 999, 9999 -> {
                Handler(Looper.getMainLooper()).post {

                }
            }
            8007 -> {
                Handler(Looper.getMainLooper()).post {

                }
            }
        }

        return originalResponse
    }
}